package com.genexususa.eo.google.connection;

import com.genexususa.eo.google.data.*;
import com.google.api.ads.adwords.axis.v201406.cm.*;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.util.ArrayList;


public class ConversionTrackerManager {


    private static final int PAGE_SIZE = 5000;
    private String _clientId;

    public void SetClientId(String clientId) {
        this._clientId = clientId;
    }

    public String GetClientId() {
        return _clientId;
    }

    public void Finalize() {

        SessionController sc = SessionController.getInstance();
        sc.RemoveSession(_clientId);
    }


    public String AddConversionTracker(String xml) {

        try {
            String result = "";
            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();
            GA_Result res = new GA_Result();
            Util util = new Util();
            Document doc = util.loadXMLFromString(xml);
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile("//GA_ConversionTracker");
            Object conversionTrackerObjects = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList conversionTrackerNodes = (NodeList) conversionTrackerObjects;
            ArrayList<GA_ResultItem> conversionTrackers = new ArrayList<GA_ResultItem>();
            if (conversionTrackerNodes.getLength() > 0) {
                for (int i = 0; i < conversionTrackerNodes.getLength(); i++) { // For all GA_ConversionTracker Nodes
                    Node n = conversionTrackerNodes.item(i);
                    NodeList children = n.getChildNodes();
                    if (children.getLength() > 0) {
                        AdWordsConversionTracker conversionTracker = new AdWordsConversionTracker();
                        GA_ResultItem gaConversionTracker = new GA_ResultItem();
                        for (int j = 0; j < children.getLength(); j++) {
                            if (children.item(j).getNodeName().equalsIgnoreCase("ConversionTrackerGxId")) {
                                gaConversionTracker.ConversionTrackerGxId = Long.parseLong(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("Name")) {
                                conversionTracker.setName(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("Status")) {
                                if (children.item(j).getTextContent().equalsIgnoreCase("E")) {
                                    conversionTracker.setStatus(ConversionTrackerStatus.ENABLED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("D")) {
                                    conversionTracker.setStatus(ConversionTrackerStatus.DISABLED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("H")) {
                                    conversionTracker.setStatus(ConversionTrackerStatus.HIDDEN);
                                }
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("Category")) {
                                if (children.item(j).getTextContent().equalsIgnoreCase("D")) {
                                    conversionTracker.setCategory(ConversionTrackerCategory.DEFAULT);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("PV")) {
                                    conversionTracker.setCategory(ConversionTrackerCategory.PAGE_VIEW);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("P")) {
                                    conversionTracker.setCategory(ConversionTrackerCategory.PURCHASE);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("S")) {
                                    conversionTracker.setCategory(ConversionTrackerCategory.SIGNUP);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("L")) {
                                    conversionTracker.setCategory(ConversionTrackerCategory.LEAD);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("R")) {
                                    conversionTracker.setCategory(ConversionTrackerCategory.REMARKETING);
                                }
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("viewthroughLookbackWindow")) {
                                conversionTracker.setViewthroughLookbackWindow(Integer.parseInt(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("isProductAdsChargeable")) {
                                conversionTracker.setIsProductAdsChargeable(Boolean.parseBoolean(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("productAdsChargeableConversionWindow")) {
                                conversionTracker.setProductAdsChargeableConversionWindow(Integer.parseInt(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("markupLanguage")) {
                                if (children.item(j).getTextContent().equalsIgnoreCase("H")) {
                                    conversionTracker.setMarkupLanguage(AdWordsConversionTrackerMarkupLanguage.HTML);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("C")) {
                                    conversionTracker.setMarkupLanguage(AdWordsConversionTrackerMarkupLanguage.CHTML);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("X")) {
                                    conversionTracker.setMarkupLanguage(AdWordsConversionTrackerMarkupLanguage.XHTML);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("W")) {
                                    conversionTracker.setMarkupLanguage(AdWordsConversionTrackerMarkupLanguage.WML);
                                }
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("textFormat")) {
                                if (children.item(j).getTextContent().equalsIgnoreCase("OL")) {
                                    conversionTracker.setTextFormat(AdWordsConversionTrackerTextFormat.ONE_LINE);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("TL")) {
                                    conversionTracker.setTextFormat(AdWordsConversionTrackerTextFormat.TWO_LINE);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("H")) {
                                    conversionTracker.setTextFormat(AdWordsConversionTrackerTextFormat.HIDDEN);
                                }
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("conversionPageLanguage")) {
                                conversionTracker.setConversionPageLanguage(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("backgroundColor")) {
                                conversionTracker.setBackgroundColor(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("trackingCodeType")) {
                                if (children.item(j).getTextContent().equalsIgnoreCase("W")) {
                                    conversionTracker.setTrackingCodeType(AdWordsConversionTrackerTrackingCodeType.WEBPAGE);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("C")) {
                                    conversionTracker.setTrackingCodeType(AdWordsConversionTrackerTrackingCodeType.CLICK_TO_CALL);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("A")) {
                                    conversionTracker.setTrackingCodeType(AdWordsConversionTrackerTrackingCodeType.ANDROID_REMARKETING);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("AP")) {
                                    conversionTracker.setTrackingCodeType(AdWordsConversionTrackerTrackingCodeType.APPLE_IOS_REMARKETING);
                                }
                            }
                        }
                        gaConversionTracker.ConversionTracker = conversionTracker;
                        conversionTrackers.add(gaConversionTracker);
                    }
                }
                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();
                for (GA_ResultItem conversionTracker : conversionTrackers) {
                    GA_ResultItem createdConversionTracker = new GA_ResultItem();
                    createdConversionTracker.ConversionTrackerGxId = conversionTracker.ConversionTrackerGxId;
                    ConversionTrackerOperation operation = new ConversionTrackerOperation();
                    operation.setOperator(Operator.ADD);
                    operation.setOperand(conversionTracker.ConversionTracker);
                    ConversionTrackerOperation[] operations = new ConversionTrackerOperation[]{operation};
                    ConversionTrackerServiceInterface conversionTrackerService = sf.GetConversionTrackerService(this.GetClientId());
                    try {
                        ConversionTrackerReturnValue returnValue = conversionTrackerService.mutate(operations);
                        Thread.sleep(1000);
                        createdConversionTracker.ConversionTrackerId = returnValue.getValue(0).getId();
                        created.add(createdConversionTracker);
                    } catch (ApiException apiException) {
                        ApiError[] apiErrors = apiException.getErrors();
                        createdConversionTracker.ConversionTrackerId = 0L;
                        createdConversionTracker.HasError = true;
                        for (ApiError apiError : apiErrors) {
                            ErrorsStruct errors = new ErrorsStruct();
                            errors.Message = apiError.getErrorString();
                            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
                            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
                            err.ErrorString = apiError.getErrorString();
                            err.fieldPath = apiError.getFieldPath();
                            err.Reason = apiException.getFaultReason();
                            err.Trigger = apiError.getTrigger();
                            err.Type = apiError.getApiErrorType();
                            errors.Errors.add(err);
                            createdConversionTracker.Errors = errors;
                            created.add(createdConversionTracker);
                        }
                    }
                }
                try {
                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    StringWriter sw = new StringWriter();
                    res.Items = created;
                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }
            }
            return result;
        } catch (Exception exc) {
            GA_Result res = new GA_Result();
            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();
            GA_ResultItem error = new GA_ResultItem();
            ErrorsStruct errors = new ErrorsStruct();
            errors.Message = exc.getMessage();
            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));
            err.UnknownError = st.toString();
            errors.Errors.add(err);
            error.Errors = errors;
            error.HasError = true;
            items.add(error);
            String result = "";
            try {
                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                StringWriter sw = new StringWriter();
                res.Items = items;
                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;
            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }
    }

    public String CreateAdCallMetricsConversion(String xml){
        try {
            String result = "";
            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();
            GA_Result res = new GA_Result();
            Util util = new Util();
            Document doc = util.loadXMLFromString(xml);
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile("//GA_AdCallMetricsConversion");
            Object adCallConversionObjects = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList adCallConversionNodes = (NodeList) adCallConversionObjects;
            ArrayList<GA_ResultItem> adCallConversions = new ArrayList<GA_ResultItem>();

            if (adCallConversionNodes.getLength() > 0) {
                for (int i = 0; i < adCallConversionNodes.getLength(); i++) { // For all GA_AdCallMetricsConversion Nodes
                    Node n = adCallConversionNodes.item(i);
                    NodeList children = n.getChildNodes();
                    if (children.getLength() > 0) {
                        AdCallMetricsConversion adCallMetricsConversion = new AdCallMetricsConversion();
                        GA_ResultItem gaAdCallMetricsConversion = new GA_ResultItem();
                        for (int j = 0; j < children.getLength(); j++) {
                            if (children.item(j).getNodeName().equalsIgnoreCase("AdCallMetricsConversionGxId")) {
                                gaAdCallMetricsConversion.AdCallMetricsConversionGxId = Long.parseLong(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("Name")) {
                                adCallMetricsConversion.setName(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("Status")) {
                                if (children.item(j).getTextContent().equalsIgnoreCase("E")) {
                                    adCallMetricsConversion.setStatus(ConversionTrackerStatus.ENABLED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("D")) {
                                    adCallMetricsConversion.setStatus(ConversionTrackerStatus.DISABLED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("H")) {
                                    adCallMetricsConversion.setStatus(ConversionTrackerStatus.HIDDEN);
                                }
                            }
                            if(children.item(j).getNodeName().equalsIgnoreCase("ctcLookbackWindow")){
                                adCallMetricsConversion.setCtcLookbackWindow(Integer.parseInt(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("countingType")){
                                if (children.item(j).getTextContent().equalsIgnoreCase("M")){
                                    adCallMetricsConversion.setCountingType(ConversionDeduplicationMode.MANY_PER_CLICK);
                                }
                                if (children.item(j).getTextContent().equalsIgnoreCase("O")){
                                    adCallMetricsConversion.setCountingType(ConversionDeduplicationMode.ONE_PER_CLICK);
                                }
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("defaultRevenueValue")){
                                adCallMetricsConversion.setDefaultRevenueValue(Double.parseDouble(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("alwaysUseDefaultRevenueValue")){
                                adCallMetricsConversion.setAlwaysUseDefaultRevenueValue(Boolean.parseBoolean(children.item(j).getTextContent()));
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("Category")) {
                                if (children.item(j).getTextContent().equalsIgnoreCase("D")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.DEFAULT);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("PV")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.PAGE_VIEW);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("P")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.PURCHASE);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("S")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.SIGNUP);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("L")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.LEAD);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("R")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.REMARKETING);
                                }
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("viewthroughLookbackWindow")) {
                                adCallMetricsConversion.setViewthroughLookbackWindow(Integer.parseInt(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("isProductAdsChargeable")) {
                                adCallMetricsConversion.setIsProductAdsChargeable(Boolean.parseBoolean(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("productAdsChargeableConversionWindow")) {
                                adCallMetricsConversion.setProductAdsChargeableConversionWindow(Integer.parseInt(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("phoneCallDuration")){
                                adCallMetricsConversion.setPhoneCallDuration(Long.parseLong(children.item(j).getTextContent()));
                            }
                        }

                        gaAdCallMetricsConversion.AdCallMetricsConversion = adCallMetricsConversion;
                        adCallConversions.add(gaAdCallMetricsConversion);
                    }
                }
                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();
                for (GA_ResultItem adCallMetricsConversion : adCallConversions) {
                    GA_ResultItem createdAdCallMetricsConversion = new GA_ResultItem();
                    createdAdCallMetricsConversion.AdCallMetricsConversionGxId = adCallMetricsConversion.AdCallMetricsConversionGxId;
                    ConversionTrackerOperation operation = new ConversionTrackerOperation();
                    operation.setOperator(Operator.ADD);
                    operation.setOperand(adCallMetricsConversion.AdCallMetricsConversion);
                    ConversionTrackerOperation[] operations = new ConversionTrackerOperation[]{operation};
                    ConversionTrackerServiceInterface conversionTrackerService = sf.GetConversionTrackerService(this.GetClientId());
                    try {
                        ConversionTrackerReturnValue returnValue = conversionTrackerService.mutate(operations);
                        Thread.sleep(1000);
                        createdAdCallMetricsConversion.AdCallMetricsConversionId = returnValue.getValue(0).getId();
                        createdAdCallMetricsConversion.AdCallMetricsConversionGxId = adCallMetricsConversion.AdCallMetricsConversionGxId;
                        created.add(createdAdCallMetricsConversion);
                    } catch (ApiException apiException) {

                        ApiError[] apiErrors = apiException.getErrors();
                        createdAdCallMetricsConversion.AdCallMetricsConversionId = 0L;
                        createdAdCallMetricsConversion.HasError = true;
                        for (ApiError apiError : apiErrors) {
                            ErrorsStruct errors = new ErrorsStruct();
                            errors.Message = apiError.getErrorString();
                            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
                            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
                            err.ErrorString = apiError.getErrorString();
                            err.fieldPath = apiError.getFieldPath();
                            err.Reason = apiException.getFaultReason();
                            err.Trigger = apiError.getTrigger();
                            err.Type = apiError.getApiErrorType();
                            errors.Errors.add(err);
                            createdAdCallMetricsConversion.Errors = errors;
                            created.add(createdAdCallMetricsConversion);
                        }
                    }
                }

                try {

                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    StringWriter sw = new StringWriter();
                    res.Items = created;
                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }
            }
            return result;

        } catch (Exception exc) {
            GA_Result res = new GA_Result();
            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();
            GA_ResultItem error = new GA_ResultItem();
            ErrorsStruct errors = new ErrorsStruct();
            errors.Message = exc.getMessage();
            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));
            err.UnknownError = st.toString();
            errors.Errors.add(err);
            error.Errors = errors;
            error.HasError = true;
            items.add(error);
            String result = "";
            try {
                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                StringWriter sw = new StringWriter();
                res.Items = items;
                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }
    }

    public String UpdateAdCallMetricsConversion(String xml){
        try {
            String result = "";
            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();
            GA_Result res = new GA_Result();
            Util util = new Util();
            Document doc = util.loadXMLFromString(xml);
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile("//GA_AdCallMetricsConversion");
            Object adCallConversionObjects = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList adCallConversionNodes = (NodeList) adCallConversionObjects;
            ArrayList<GA_ResultItem> adCallConversions = new ArrayList<GA_ResultItem>();

            if (adCallConversionNodes.getLength() > 0) {
                for (int i = 0; i < adCallConversionNodes.getLength(); i++) { // For all GA_AdCallMetricsConversion Nodes
                    Node n = adCallConversionNodes.item(i);
                    NodeList children = n.getChildNodes();
                    if (children.getLength() > 0) {
                        AdCallMetricsConversion adCallMetricsConversion = new AdCallMetricsConversion();
                        GA_ResultItem gaAdCallMetricsConversion = new GA_ResultItem();
                        for (int j = 0; j < children.getLength(); j++) {
                            if (children.item(j).getNodeName().equalsIgnoreCase("AdCallMetricsConversionGxId")) {
                                gaAdCallMetricsConversion.AdCallMetricsConversionGxId = Long.parseLong(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("AdCallMetricsConversionId")) {
                                adCallMetricsConversion.setId(Long.parseLong(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("Name")) {
                                adCallMetricsConversion.setName(children.item(j).getTextContent());
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("Status")) {
                                if (children.item(j).getTextContent().equalsIgnoreCase("E")) {
                                    adCallMetricsConversion.setStatus(ConversionTrackerStatus.ENABLED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("D")) {
                                    adCallMetricsConversion.setStatus(ConversionTrackerStatus.DISABLED);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("H")) {
                                    adCallMetricsConversion.setStatus(ConversionTrackerStatus.HIDDEN);
                                }
                            }
                            if(children.item(j).getNodeName().equalsIgnoreCase("ctcLookbackWindow")){
                                adCallMetricsConversion.setCtcLookbackWindow(Integer.parseInt(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("countingType")){
                                if (children.item(j).getTextContent().equalsIgnoreCase("M")){
                                    adCallMetricsConversion.setCountingType(ConversionDeduplicationMode.MANY_PER_CLICK);
                                }
                                if (children.item(j).getTextContent().equalsIgnoreCase("O")){
                                    adCallMetricsConversion.setCountingType(ConversionDeduplicationMode.ONE_PER_CLICK);
                                }
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("defaultRevenueValue")){
                                adCallMetricsConversion.setDefaultRevenueValue(Double.parseDouble(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("alwaysUseDefaultRevenueValue")){
                                adCallMetricsConversion.setAlwaysUseDefaultRevenueValue(Boolean.parseBoolean(children.item(j).getTextContent()));
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("Category")) {
                                if (children.item(j).getTextContent().equalsIgnoreCase("D")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.DEFAULT);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("PV")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.PAGE_VIEW);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("P")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.PURCHASE);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("S")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.SIGNUP);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("L")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.LEAD);
                                } else if (children.item(j).getTextContent().equalsIgnoreCase("R")) {
                                    adCallMetricsConversion.setCategory(ConversionTrackerCategory.REMARKETING);
                                }
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("viewthroughLookbackWindow")) {
                                adCallMetricsConversion.setViewthroughLookbackWindow(Integer.parseInt(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("isProductAdsChargeable")) {
                                adCallMetricsConversion.setIsProductAdsChargeable(Boolean.parseBoolean(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("productAdsChargeableConversionWindow")) {
                                adCallMetricsConversion.setProductAdsChargeableConversionWindow(Integer.parseInt(children.item(j).getTextContent()));
                            }
                            if (children.item(j).getNodeName().equalsIgnoreCase("phoneCallDuration")){
                                adCallMetricsConversion.setPhoneCallDuration(Long.parseLong(children.item(j).getTextContent()));
                            }
                        }

                        gaAdCallMetricsConversion.AdCallMetricsConversion = adCallMetricsConversion;
                        adCallConversions.add(gaAdCallMetricsConversion);
                    }
                }
                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();
                for (GA_ResultItem adCallMetricsConversion : adCallConversions) {
                    GA_ResultItem createdAdCallMetricsConversion = new GA_ResultItem();
                    createdAdCallMetricsConversion.AdCallMetricsConversionGxId = adCallMetricsConversion.AdCallMetricsConversionGxId;
                    ConversionTrackerOperation operation = new ConversionTrackerOperation();
                    operation.setOperator(Operator.SET);
                    operation.setOperand(adCallMetricsConversion.AdCallMetricsConversion);
                    ConversionTrackerOperation[] operations = new ConversionTrackerOperation[]{operation};
                    ConversionTrackerServiceInterface conversionTrackerService = sf.GetConversionTrackerService(this.GetClientId());
                    try {
                        ConversionTrackerReturnValue returnValue = conversionTrackerService.mutate(operations);
                        Thread.sleep(1000);
                        createdAdCallMetricsConversion.AdCallMetricsConversionId = returnValue.getValue(0).getId();
                        createdAdCallMetricsConversion.AdCallMetricsConversionGxId = adCallMetricsConversion.AdCallMetricsConversionGxId;
                        created.add(createdAdCallMetricsConversion);
                    } catch (ApiException apiException) {

                        ApiError[] apiErrors = apiException.getErrors();
                        createdAdCallMetricsConversion.AdCallMetricsConversionId = 0L;
                        createdAdCallMetricsConversion.HasError = true;
                        for (ApiError apiError : apiErrors) {
                            ErrorsStruct errors = new ErrorsStruct();
                            errors.Message = apiError.getErrorString();
                            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
                            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
                            err.ErrorString = apiError.getErrorString();
                            err.fieldPath = apiError.getFieldPath();
                            err.Reason = apiException.getFaultReason();
                            err.Trigger = apiError.getTrigger();
                            err.Type = apiError.getApiErrorType();
                            errors.Errors.add(err);
                            createdAdCallMetricsConversion.Errors = errors;
                            created.add(createdAdCallMetricsConversion);
                        }
                    }
                }

                try {

                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    StringWriter sw = new StringWriter();
                    res.Items = created;
                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }
            }
            return result;

        } catch (Exception exc) {
            GA_Result res = new GA_Result();
            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();
            GA_ResultItem error = new GA_ResultItem();
            ErrorsStruct errors = new ErrorsStruct();
            errors.Message = exc.getMessage();
            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));
            err.UnknownError = st.toString();
            errors.Errors.add(err);
            error.Errors = errors;
            error.HasError = true;
            items.add(error);
            String result = "";
            try {
                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                StringWriter sw = new StringWriter();
                res.Items = items;
                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }
    }

    public ArrayList<AdCallMetricsConversionReport> GetAdCallMetricsConversionReport(String clientId){
        ArrayList<AdCallMetricsConversionReport> result = new ArrayList<AdCallMetricsConversionReport>();

        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();

        try {
            ConversionTrackerServiceInterface conversionTrackerService = sf.GetConversionTrackerService(clientId);

            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));

            selector.setFields(new String[]
                    {
                            "Id", "Name", "Status", "Category", "ViewthroughLookbackWindow", "IsProductAdsChargeable", "ProductAdsChargeableConversionWindow", "CtcLookbackWindow",
                            "CountingType", "DefaultRevenueValue", "AlwaysUseDefaultRevenueValue", "PhoneCallDuration"

                    });

            ConversionTrackerPage page = null;


            try {

                do {

                    page = conversionTrackerService.get(selector);

                    if (page.getEntries() != null) {


                        for (ConversionTracker adCallMetricsConversion : page.getEntries()) {

                            AdCallMetricsConversionReport stats = new AdCallMetricsConversionReport();

                            stats.Id = adCallMetricsConversion.getId();
                            stats.Name = adCallMetricsConversion.getName();
                            stats.Category = adCallMetricsConversion.getCategory().getValue();
                            stats.Status = adCallMetricsConversion.getStatus().getValue();
                            stats.ViewthroughLookbackWindow = adCallMetricsConversion.getViewthroughLookbackWindow();
                            stats.IsProductAdsChargeable = adCallMetricsConversion.getIsProductAdsChargeable();
                            stats.ProductAdsChargeableConversionWindow = adCallMetricsConversion.getProductAdsChargeableConversionWindow();
                            stats.CtcLookbackWindow = adCallMetricsConversion.getCtcLookbackWindow();
                            stats.CountingType = adCallMetricsConversion.getCountingType().getValue();
                            stats.DefaultRevenueValue = adCallMetricsConversion.getDefaultRevenueValue();
                            stats.AlwaysUseDefaultRevenueValue = adCallMetricsConversion.getAlwaysUseDefaultRevenueValue();
                            stats.PhoneCallDuration = ((AdCallMetricsConversion) adCallMetricsConversion).getPhoneCallDuration();

                            result.add(stats);

                        }


                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());
            } catch (RemoteException ex) {

            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

        return result;
    }

    protected ArrayList<ConversionTrackerReport> GetConversionTrackerStats(String clientId) {

        ArrayList<ConversionTrackerReport> result = new ArrayList<ConversionTrackerReport>();

        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();

        try {
            ConversionTrackerServiceInterface conversionTrackerService = sf.GetConversionTrackerService(clientId);

            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));

            selector.setFields(new String[]
                    {
                            "Id", "Name", "MostRecentConversionDate", "NumConversionEvents", "NumConvertedClicks", "ProductAdsChargeableConversionWindow", "Status",
                            "ViewthroughConversionDeDupSearch", "ViewthroughLookbackWindow", "Category", "ConversionValue"

                    });

            ConversionTrackerPage page = null;


            try {

                do {

                    page = conversionTrackerService.get(selector);

                    if (page.getEntries() != null) {


                        for (ConversionTracker conversionTracker : page.getEntries()) {

                            ConversionTrackerReport stats = new ConversionTrackerReport();

                            stats.Id = conversionTracker.getId();
                            stats.Name = conversionTracker.getName();
                            stats.Category = conversionTracker.getCategory().getValue();
                            stats.NumConversionEvents = conversionTracker.getStats().getNumConversionEvents();
                            stats.NumConvertedClicks = conversionTracker.getStats().getNumConvertedClicks();

                            stats.ConversionValue = conversionTracker.getStats().getConversionValue();
                            stats.ProductAdsChargeableConversionWindow = conversionTracker.getProductAdsChargeableConversionWindow();
                            stats.Status = conversionTracker.getStatus().getValue();
                            //stats.ViewthroughConversionDeDupSearch = conversionTracker.getViewthroughConversionDeDupSearch();
                            stats.ViewthroughLookbackWindow = conversionTracker.getViewthroughLookbackWindow();


                            result.add(stats);

                        }


                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());
            } catch (RemoteException ex) {

            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

        return result;

    }

}
